package cn.coisini.service.impl;

import cn.coisini.mapper.ArticleMapper;
import cn.coisini.model.common.dtos.Result;
import cn.coisini.model.common.enums.ResultEnum;
import cn.coisini.model.dto.CategoryDto;
import cn.coisini.model.pojo.Article;
import cn.coisini.model.vo.QueryVo;
import cn.coisini.model.vo.TagVo;
import cn.coisini.service.*;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.coisini.model.common.constants.AdminConstants.CREATE_TIME;
import static cn.coisini.model.common.constants.AdminConstants.TRUE;
import static cn.coisini.utils.JwtUtil.getUserIdFromToken;

/**
 * @author xiangshaw
 * Description: 文章视图接口实现
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class ArticleViewServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleViewService {

    private final TagService tagService;
    private final UserService userService;
    private final CategoryService categoryService;
    private final ArticleService articleService;

    /**
     * 文章视图列表查询
     */
    @Override
    public Result<Object> getArticleViewList(QueryVo queryVo) {
        // 构建查询条件
        QueryWrapper<Article> articleQueryWrapper = articleViewQueryWrapper(queryVo);
        // 分页查询文章列表
        Page<Article> page = new Page<>(queryVo.getCurrent(), queryVo.getLimit());
        Page<Article> articlePage = page(page, articleQueryWrapper);

        // 查询文章列表
        List<Article> articles = articlePage.getRecords();
        if (articles.isEmpty()) {
            return Result.ok(List.of());
        }

        // 提取所有文章的ID和创建用户ID、分类ID
        List<String> articleIds = articles.stream()
                .map(Article::getId)
                .toList();
        List<String> userIds = articles.stream()
                .map(Article::getCreateUser)
                .toList();
        List<String> categoryIds = articles.stream()
                .map(Article::getCategoryId)
                .toList();

        // 批量获取用户名、分类名、标签名
        Map<String, String> userIdToNameMap = userService.getUserNamesByIds(userIds);
        Map<String, String> categoryIdToNameMap = categoryService.getCategoryNamesByIds(categoryIds);
        Map<String, List<TagVo>> articleIdToTagMap = tagService.getTagNamesByArticleIds(articleIds);

        // 设置创建用户、分类、标签、标签颜色
        articles.forEach(article -> {
            article.setCreateUser(userIdToNameMap.get(article.getCreateUser()));
            article.setCategoryName(categoryIdToNameMap.get(article.getCategoryId()));
            // 设置标签信息
            List<TagVo> tagInfos = articleIdToTagMap.get(article.getId());
            if (tagInfos != null) {
                article.setTagName(tagInfos.stream()
                        .map(TagVo::getTagName)
                        .toList());
                article.setTagColor(tagInfos.stream()
                        .map(TagVo::getColor)
                        .collect(Collectors.joining(",")));
            }
        });
        return Result.ok(articles);
    }

    private QueryWrapper<Article> articleViewQueryWrapper(QueryVo queryVo) {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        // 提取查询条件
        String categoryId = queryVo.getCategoryId();
        String keyword = queryVo.getKeyword();
        // 分类ID模糊查询
        if (CharSequenceUtil.isNotBlank(categoryId)) {
            wrapper.eq("category_id", categoryId);
        }
        // 标题或内容模糊查询
        if (CharSequenceUtil.isBlank(keyword)) {
            wrapper.like("title", keyword).or().like("content", keyword);
        }
        // 状态和时间倒序排序
        wrapper.eq("state", TRUE).orderByDesc(CREATE_TIME);
        return wrapper;
    }

    /**
     * 分类视图列表查询
     */
    @Override
    public Result<List<Map<String, Object>>> getCategoryViewList() {
        // 如果用户登录则返回用户的分类
        String userId = getUserIdFromToken();
        if (CharSequenceUtil.isBlank(userId)) {
            // 默认返回用户1的分类
            return Result.ok(categoryService.getCategoryByUserId("1"));
        }
        return Result.ok(categoryService.getCategoryByUserId(userId));

    }

    /**
     * 推荐分类列表查询
     */
    @Override
    public Result<List<Map<String, Object>>> getRecommendCategoryViewList() {
        // 如果用户登录则返回用户的分类
        String userId = getUserIdFromToken();
        if (CharSequenceUtil.isBlank(userId)) {
            // 默认返回用户1的推荐分类
            return Result.ok(categoryService.getRcategoryByUserId("1"));
        }
        return Result.ok(categoryService.getRcategoryByUserId(userId));
    }

    /**
     * 添加或取消推荐分类
     */
    @Override
    public Result<ResultEnum> updateRecommendCategory(CategoryDto categoryDto) {
        String userId = getUserIdFromToken();
        if (CharSequenceUtil.isBlank(userId)) {
            return Result.error(ResultEnum.REQUIRES_LOGIN, "需要登录之后才能保存数据");
        }
        return categoryService.updateRecommendCategory(categoryDto);
    }

    /**
     * 文章详情
     */
    @Override
    public Result<Article> getArticleViewDetail(String id) {
        return articleService.getArticleById(id);
    }
}
